package cn.com.jdyun.controller;

import cn.com.jdyun.dto.UserCredit;
import cn.com.jdyun.exception.BdexGatewayException;
import cn.com.jdyun.interceptor.Auth;
import cn.com.jdyun.mapper.ext.ExtSysConfigMapper;
import cn.com.jdyun.pojo.Gains;
import cn.com.jdyun.pojo.RewardPoints;
import cn.com.jdyun.pojo.SysConfig;
import cn.com.jdyun.pojo.UserWallet;
import cn.com.jdyun.service.GainsService;
import cn.com.jdyun.service.LotteryService;
import cn.com.jdyun.service.MinerService;
import cn.com.jdyun.service.RefereeService;
import cn.com.jdyun.service.SysConfigService;
import cn.com.jdyun.service.UserService;
import cn.com.jdyun.service.UserWalletService;
import cn.com.jdyun.util.ConfigParam;
import cn.com.jdyun.util.Constant;
import cn.com.jdyun.util.RedisUtil;
import cn.com.jdyun.util.WebConstants;
import cn.com.jdyun.util.reponse.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yzping
 * @date Created in 下午 4:24 2018/8/17 0017
 */
@RestController
public class MinerController {

    @Autowired
    MinerService minerService;
    @Autowired
    UserService userService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private LotteryService lotteryService;
    @Autowired
    private UserWalletService userWalletService;
    @Autowired
    RefereeService refereeService;
    @Autowired
    private GainsService gainsService;
    @Autowired
    private ExtSysConfigMapper sysConfigMapper;

    /**
     * 获取每日签到得到的奖励
     *
     * @return
     */
    @Auth
    @PostMapping("/Miner/signDailyReplay")
    public Result signDailyReplay(HttpSession session) throws BdexGatewayException {
        Result result = new Result();
        UserCredit userCredit = (UserCredit) session.getAttribute(Constant.ACCOUNT_Mining);
        /**
         * 1.检查矿池中是否有足够的Tex
         * 2.一天只能签到一次
         * 3.每天得到的奖励是固定的
         * 4.得到的奖励划入总金额中
         */
        String dailyReward = minerService.checkMineralPoolTex(userCredit.getId(), userCredit.getSuperNode());

        result.setData(dailyReward);
        return result;
    }

    /**
     * 获取矿池中总Tex以及用户今日所得
     *
     * @return
     */
    @Auth
    @PostMapping("/Miner/getMineralPoolTex")
    public Result getMineralPoolTex(HttpSession session) throws BdexGatewayException {
        UserCredit userCredit = (UserCredit) session.getAttribute(Constant.ACCOUNT_Mining);
        Result result = new Result();
        Map<String, Object> map = new HashMap<>();
        String mineralPoolSSSP = sysConfigService.queryConfigInitValue(ConfigParam.MINER_POOL_AMOUNT);
        String mineralPoolTEX = sysConfigService.queryConfigInitValue(ConfigParam.MINER_POOL_AMOUNT_TEX);
        //矿池剩余总额
        map.put("poolAmount_sssp", mineralPoolSSSP);
        map.put("poolAmount_tex", mineralPoolTEX);
        //今日所得，以及挖矿比例
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        String date = WebConstants.dateFormat.format(calendar.getTime());
        Gains g_sssp = gainsService.queryCurBalance(date, userCredit.getId(),Constant.COINTYPE_SSSP);
        Gains g_tex = gainsService.queryCurBalance(date, userCredit.getId(),Constant.COINTYPE_TEX);
        if (g_sssp == null) {
            map.put("miningCoin_sssp", WebConstants.numberFormat("0.00","0"));
            map.put("miningRate_sssp", WebConstants.numberFormat("0.00","0"));
        } else {
            map.put("miningCoin_sssp", WebConstants.numberFormat("0.00", g_sssp.getVested()));
            map.put("miningRate_sssp", WebConstants.numberFormat("0.00",g_sssp.getRate()));
        }
        if (g_tex == null) {
            map.put("miningCoin_tex", WebConstants.numberFormat("0.00","0"));
            map.put("miningRate_tex", WebConstants.numberFormat("0.00","0"));
        } else {
            map.put("miningCoin_tex", WebConstants.numberFormat("0.00", g_tex.getVested()));
            map.put("miningRate_tex", WebConstants.numberFormat("0.00",g_tex.getRate()));
        }
        result.setData(map);
        return result;
    }

    /**
     * 挖矿
     *
     * @return
     * @throws BdexGatewayException
     */
    @Auth
    @PostMapping("/Miner/minerInfo")
    public Result minerGains(HttpSession session) throws BdexGatewayException {
        SysConfig smallMinerConfig = sysConfigMapper.selectByCode(Constant.smallMiner);
        SysConfig texSmallMinerConfig = sysConfigMapper.selectByCode(Constant.texSmallMiner);
        SysConfig largeMiningMachineConfig = sysConfigMapper.selectByCode(Constant.largeMiningMachine);
        SysConfig texLargeMiningMachineConfig = sysConfigMapper.selectByCode(Constant.texLargeMiningMachine);
        UserCredit userCredit = (UserCredit) session.getAttribute(Constant.ACCOUNT_Mining);
        Result result = new Result();
        Map<String, Object> map = new HashMap<>();

        //我sssp的荣誉值
        RewardPoints rp = lotteryService.queryUserRewardPoints(userCredit.getId(), Constant.COINTYPE_SSSP);
        if (rp == null) {
            map.put("honor_sssp", WebConstants.numberFormat("0.00","0"));
        } else {
            map.put("honor_sssp", WebConstants.numberFormat("0.00",rp.getCoinAmount()));
        }
        //我Tex的荣誉值
        RewardPoints rpTex = lotteryService.queryUserRewardPoints(userCredit.getId(), Constant.COINTYPE_TEX);
        if (rpTex == null) {
            map.put("honor_tex", WebConstants.numberFormat("0.00","0"));
        } else {
            map.put("honor_tex", WebConstants.numberFormat("0.00",rpTex.getCoinAmount()));
        }
        map.put("level_sssp", "注册用户");
        //我的锁仓,收益,等级，排名
        UserWallet userWalletSssp = userWalletService.queryByUserIdAndConiType(userCredit.getId(), Constant.COINTYPE_SSSP);
        UserWallet userWalletTex = userWalletService.queryByUserIdAndConiType(userCredit.getId(), Constant.COINTYPE_TEX);

        if (userWalletTex == null) {
            map.put("lockedCoin_tex", WebConstants.numberFormat("0.00","0"));
            map.put("miningCoin_tex", WebConstants.numberFormat("0.00","0"));
            map.put("level_tex", "注册用户");
            int rank = userWalletService.queryRankByAmountAndConiType(BigDecimal.valueOf(0), Constant.COINTYPE_TEX);
            map.put("rank_tex", rank + 1);
        } else {
            map.put("lockedCoin_tex", WebConstants.numberFormat("0.00",userWalletTex.getLockedCoin().toString()));
            map.put("miningCoin_tex", WebConstants.numberFormat("0.00",userWalletTex.getMingCoin()));
            BigDecimal cp_tex = userWalletTex.getLockedCoin();
            if(userCredit.getTexLevel() == 0) {
                if (cp_tex.subtract(new BigDecimal(texSmallMinerConfig.getInitValue())).doubleValue() >= 0 && cp_tex.subtract(new BigDecimal(texLargeMiningMachineConfig.getInitValue())).doubleValue() < 0) {
                    //微挖矿
                    map.put("level_tex", "tex小矿机");
                } else if (cp_tex.subtract(new BigDecimal(texLargeMiningMachineConfig.getInitValue())).doubleValue() >= 0) {
                    //强挖矿
                    map.put("level_tex", "tex大矿机");
                }
                //超级节点
                if (refereeService.checkSuperNode(userCredit.getId(),Constant.COINTYPE_TEX)) {
                    map.put("level_tex", "tex超级节点");
                }
                //合伙人
                if (refereeService.checkPartner(userCredit.getId())) {
                    map.put("level_tex", "tex合伙人");
                }
            }else {
                if(userCredit.getTexLevel() == 1) {
                    map.put("level_tex", "tex注册用户");
                }
                if(userCredit.getTexLevel() == 2) {
                    map.put("level_tex", "tex小矿机");
                }
                if(userCredit.getTexLevel() == 3) {
                    map.put("level_tex", "tex大矿机");
                }
                if(userCredit.getTexLevel() == 4) {
                    map.put("level_tex", "tex超级节点");
                }
                if(userCredit.getTexLevel() == 5) {
                    map.put("level_tex", "tex合伙人");
                }
            }

            int rank = userWalletService.queryRankByAmountAndConiType(cp_tex, Constant.COINTYPE_TEX);
            map.put("rank_tex", rank + 1);
        }

        if (userWalletSssp == null) {
            map.put("lockedCoin_sssp", WebConstants.numberFormat("0.00","0"));
            map.put("miningCoin_sssp", WebConstants.numberFormat("0.00","0"));
            map.put("level_sssp", "注册用户");
            int rank = userWalletService.queryRankByAmountAndConiType(BigDecimal.valueOf(0), Constant.COINTYPE_SSSP);
            map.put("rank_sssp", rank + 1);
        } else {
            map.put("lockedCoin_sssp", WebConstants.numberFormat("0.00",userWalletSssp.getLockedCoin().toString()));
            map.put("miningCoin_sssp", WebConstants.numberFormat("0.00",userWalletSssp.getMingCoin()));
            BigDecimal cp = userWalletSssp.getLockedCoin();
            if(userCredit.getTexLevel() == 0) {
                if (cp.subtract(new BigDecimal(smallMinerConfig.getInitValue())).doubleValue() >= 0 && cp.subtract(new BigDecimal(largeMiningMachineConfig.getInitValue())).doubleValue() < 0) {
                    //微挖矿
                    map.put("level_sssp", "sssp小矿机");
                } else if (cp.subtract(new BigDecimal(largeMiningMachineConfig.getInitValue())).doubleValue() >= 0) {
                    //强挖矿
                    map.put("level_sssp", "sssp大矿机");
                }
                //超级节点
                if (refereeService.checkSuperNode(userCredit.getId(),Constant.COINTYPE_SSSP)) {
                    map.put("level_sssp", "sssp超级节点");
                }
                //合伙人
                if (refereeService.checkPartner(userCredit.getId())) {
                    map.put("level_sssp", "sssp合伙人");
                }
            }else {
            	if(userCredit.getTexLevel() == 1) {
            		map.put("level_sssp", "sssp注册用户");
            	}
            	if(userCredit.getTexLevel() == 2) {
            		map.put("level_sssp", "sssp小矿机");
            	}
            	if(userCredit.getTexLevel() == 3) {
            		map.put("level_sssp", "sssp大矿机");
            	}
            	if(userCredit.getTexLevel() == 4) {
            		map.put("level_sssp", "sssp超级节点");
            	}
            	if(userCredit.getTexLevel() == 5) {
            		map.put("level_sssp", "sssp合伙人");
            	}
            }
            
            int rank = userWalletService.queryRankByAmountAndConiType(cp, Constant.COINTYPE_SSSP);
            map.put("rank_sssp", rank + 1);
        }

        //获取SSSP矿池信息
        //剩余
        map.put("poolAmount_sssp", WebConstants.numberFormat("0.00",sysConfigService.queryConfigInitValue(ConfigParam.MINER_POOL_AMOUNT)));
        //初始化值
        map.put("poolAmountInit_sssp", WebConstants.numberFormat("0.00",sysConfigService.queryConfigInitValue(ConfigParam.MINER_POOL_AMOUNT_INIT)));
        //获取Tex矿池信息
        //剩余
        map.put("poolAmount_tex", WebConstants.numberFormat("0.00",sysConfigService.queryConfigInitValue(ConfigParam.MINER_POOL_AMOUNT_TEX)));
        //初始化值
        map.put("poolAmountInit_tex", WebConstants.numberFormat("0.00",sysConfigService.queryConfigInitValue(ConfigParam.MINER_POOL_AMOUNT_INIT_TEX)));

        result.setData(map);
        return result;
    }

    /**
     * 获取用户的挖矿记录
     *
     * @param session
     * @return
     * @throws Exception
     */
    @Auth
    @PostMapping("/Miner/gainsRecords")
    public Result gainsRecords(Integer pageNumber, Integer pageSize, HttpSession session) throws Exception {

        UserCredit userCredit = (UserCredit) session.getAttribute(Constant.ACCOUNT_Mining);

        PageHelper.startPage(pageNumber, pageSize);

        Page<Gains> page = gainsService.pageData(userCredit.getId());

        return Result.success(page.toPageInfo());
    }

}
